<template>
  <div class="dict-check-root">
    <div :class="[`dict-item`,`dict-item-${id}`,`dict-item-${id}-${item.value}`]" @click="itemClick(item)"
         v-for="(item,index) in dictData"
         :key="index">
      {{ item.label }}
    </div>
  </div>
</template>

<script>
import {isArr} from "@/utils/arrayUtil";
import guid from "@/utils/guid";

export default {
  props: {
    dictData: {
      type: Array
    },
    value: {
      type: [Number, String, Array]
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      checkData: null,
      id: `p-${guid()}`
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val == this.checkData) return;
        let {multiple} = this
        this.checkData = val
        let owner = this
        this.$nextTick(() => {
          if (multiple) {
            if (isArr(owner.checkData)) {
              owner.checkData.forEach(dictValue => {
                owner.changeClassList(dictValue)
              });
            } else {
              owner.changeClassList(null)
            }
          } else {
            owner.changeClassList(owner.checkData)
          }
        })

      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    itemClick(dict) {
      let {multiple} = this
      if (multiple) {
        this.checkData = isArr(this.checkData) ? this.checkData : []
        if (this.checkData.some(item => item == dict.value)) {
          this.checkData = _.filter(_.cloneDeep(this.checkData), item => item != dict.value)
        } else {
          this.checkData.push(dict.value)
        }
      } else {
        this.checkData = dict.value
      }
      this.$emit('change', this.checkData)
      this.changeClassList(dict.value)
    },
    changeClassList(dictValue) {
      let {multiple, id} = this
      let domList = document.getElementsByClassName(`dict-item-${id}`)
      if (dictValue == null || dictValue == '') {
        if (isArr(Array.from(domList))) {
          Array.from(domList).forEach(cDom => {
            cDom.classList.remove('active')
          })
        }
      }
      let dom = document.querySelector(`.dict-item-${id}-${dictValue}`);
      if (!dom) return;
      if (Array.from(dom.classList).some(className => className == 'active')) {
        if (multiple) {
          dom.classList.remove('active')
        }
      } else {
        dom.classList.add('active')
      }
      if (!multiple) {
        if (isArr(Array.from(domList))) {
          Array.from(domList).forEach(cDom => {
            if (!Array.from(cDom.classList).some(className => className == `dict-item-${id}-${dictValue}`)) {
              cDom.classList.remove('active')
            }
          })
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/businessTheme.scss";


</style>
